package com.training.bt.user.service;

import java.time.LocalDateTime;
import java.util.UUID;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.training.bt.user.dto.UserLoginDTO;
import com.training.bt.user.dto.UserRegisterDTO;

import lombok.RequiredArgsConstructor;

import com.training.bt.enums.Role;
import com.training.bt.mapper.UserMapper;
import com.training.bt.mapper.UserPointMapper;
import com.training.bt.security.util.SecurityUtils;
import com.training.bt.entity.User;
import com.training.bt.entity.UserPoint;

import org.springframework.http.HttpStatus;

import org.springframework.web.server.ResponseStatusException;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserPointMapper userPointMapper;
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public User login(UserLoginDTO dto) {
        User user = userMapper.findByEmail(dto.getEmail());
        if (user == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "邮箱未注册");
        }

        if (!passwordEncoder.matches(dto.getPassword(), user.getPassword())) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "密码错误");
        }

        return user;
    }

    @Override
    public void register(UserRegisterDTO dto) {
        if (userMapper.existsByUsername(dto.getUsername()) == 1) {
            throw new ResponseStatusException(HttpStatus.CONFLICT, "用户名已存在");
        }
        if (userMapper.existsByEmail(dto.getEmail()) == 1) {
            throw new ResponseStatusException(HttpStatus.CONFLICT, "邮箱已存在");
        }
        User inviter = userMapper.findByPasskey(dto.getPasskey());
        if (inviter == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "邀请码无效");
        }

        String passkey = UUID.randomUUID().toString().replace("-", "");

        User user = User.builder()
                .username(dto.getUsername())
                .password(passwordEncoder.encode(dto.getPassword()))
                .email(dto.getEmail())
                .role(Role.LEVEL_1) // 默认角色
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .passkey(passkey)
                .build();

        userMapper.insert(user);

        user = userMapper.findByEmail(dto.getEmail());

        UserPoint userPoint = new UserPoint();
        userPoint.setUserId(user.getId());
        userPoint.setLastSeedingUpdate(LocalDateTime.now());

        userPointMapper.insert(userPoint);
    }

    @Override
    public User getRole() {
        User user = SecurityUtils.getCurrentUser();
        return userMapper.selectById(user.getId());
    }

    @Override
    public User getOther(Long id) {
        User user = userMapper.selectById(id);
        return user;
    }

}
